import 'package:get/get.dart';
import '../service/invite_service.dart';

class InviteController extends GetxController {
  final InviteService _inviteService = InviteService();
  
  // 响应式数据 - 根据API数据结构
  final RxInt inviteShare = 0.obs;              // 邀请分成比例
  final RxString shareUrl = ''.obs;             // 分享链接
  final RxString referralReward = '0'.obs;      // 推荐奖励（保持字符串格式以保持精度）
  final RxInt friendNum = 0.obs;                // 邀请的朋友数量
  final RxBool isLoading = false.obs;
  
  // 用户邀请码（从AuthController或其他地方获取）
  final RxString userInviteCode = ''.obs;
  
  @override
  void onInit() {
    super.onInit();
    loadInviteInfo();
  }
  
  /// 加载邀请信息
  Future<void> loadInviteInfo() async {
    try {
      isLoading.value = true;
      final response = await _inviteService.getInviteInfo();
      
      if (response.isSuccess && response.data != null) {
        final data = response.data!;
        
        inviteShare.value = data['invite_share'] ?? 0;
        shareUrl.value = data['share_url'] ?? '';
        referralReward.value = data['referral_reward'] ?? '0';
        friendNum.value = data['friend_num'] ?? 0;
        
        // 如果API返回邀请码，也可以在这里设置
        if (data.containsKey('invite_code')) {
          userInviteCode.value = data['invite_code'] ?? '';
        }
        
        // 确保UI更新
        update();
      }
    } catch (e) {
      // Get.snackbar('error'.tr, 'load_invite_info_failed'.tr);
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 提交邀请码
  Future<bool> submitInviteCode(String inviteCode) async {
    try {
      isLoading.value = true;
      final response = await _inviteService.submitInviteCode(inviteCode);
      
      if (response.isSuccess) {
        // Get.snackbar('success'.tr, 'invite_code_applied_success'.tr);
        await loadInviteInfo(); // 重新加载数据
        return true;
      } else {
        // Get.snackbar('error'.tr, response.message);
        return false;
      }
    } catch (e) {
      // Get.snackbar('error'.tr, 'submit_invite_code_failed'.trParams({'error': e.toString()}));
      return false;
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 刷新数据
  Future<void> refreshData() async {
    await loadInviteInfo();
  }
  
  /// 格式化推荐奖励显示
  String get formattedReferralReward {
    try {
      double reward = double.parse(referralReward.value);
      return reward.toStringAsFixed(12);
    } catch (e) {
      return referralReward.value;
    }
  }
}